package com.zzw.algorithm;

//单向链表
public class LinkList<T> {

    private Node head;
    private Node last;

    public LinkList() {
    }

    public void add(T data){
        Node node = new Node(data);
        final Node l = last;
        last = node;
        if (l == null){
            head = node;
        }
        else {
            l.next = node;
            //l.next = last;
        }
    }

    //头插法
    public Node reverse(){
        Node h = head;
        if(h == null){
            return h;
        }
        Node prev = null;
        Node next = null;
        while(h != null){
            next = h.next;
            h.next = prev;
            prev = h;
            h = next;
        }
        return prev;
    }

    public Node reverse(Node node) {
        if (node.next == null)
            return node;
        Node prevNode = reverse(node.next);
        Node temp = node.next;
        temp.next = node;
        node.next = null;
        return prevNode;
    }

    public void iterator(){
        if(head == null){
            return;
        }
        while (head != null){
            System.out.println(head.data);
            head = head.next;
        }
    }

    public void iterator(Node node){
        if(node == null){
            return;
        }
        while (node != null){
            System.out.println(node.data);
            node = node.next;
        }
    }

    public static void main(String[] args) {
        LinkList<Integer> linkList = new LinkList<>();
        linkList.add(1);
        linkList.add(2);
        linkList.add(3);
        linkList.add(4);
        linkList.add(5);
        Node reverse = linkList.reverse();
        linkList.iterator(reverse);
    }

    private static class Node<E>{
        private E data;
        private Node next;

        public Node() {
        }

        public Node(E data) {
            this.data = data;
        }

        public Node(E data, Node next) {
            this.data = data;
            this.next = next;
        }

        public E getData() {
            return data;
        }

        public void setData(E data) {
            this.data = data;
        }

        public Node getNext() {
            return next;
        }

        public void setNext(Node next) {
            this.next = next;
        }
    }
}
